/*
 * moving_point.c
 *
 *  Created on: Apr 5, 2013
 *      Author: filipe
 */
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>

int view_width = 200;
int view_height = 200;

int first_iteraction = 1;

int animation_update_period = 50; // ms
double time_diff_per_animation_update = 50; // s
double radial_velocity = 0.02; // m/s
double angular_velocity = 1.0; // rad/s
double last_radius = 0.0;
double last_angle = 0.0;

double max_radius;

void
Desenha()
{
	double radius = last_radius + time_diff_per_animation_update * radial_velocity;
	double angle = last_angle + time_diff_per_animation_update * angular_velocity;

	if (angle > (2 * M_PI))
		angle = angle - (2 * M_PI);

	if (angle < 0)
		angle += (2 * M_PI);

	if (radius <= 1)
		radial_velocity = (radial_velocity < 0) ? (-radial_velocity) : (radial_velocity);

	if (radius >= max_radius)
		radial_velocity = (radial_velocity > 0) ? (-radial_velocity) : (radial_velocity);

	double x = cos(angle) * radius;
	double y = sin(angle) * radius;

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glClear(GL_COLOR_BUFFER_BIT);

	glPointSize((radius / max_radius) * 10 + 1);
	glBegin(GL_POINTS);
		//glColor3f(((double) rand()) / (double) RAND_MAX, ((double) rand()) / (double) RAND_MAX, ((double) rand()) / (double) RAND_MAX);
		glColor3f(1.0, 0.0, 0.0);
		glVertex2i(x, y);
	glEnd();

	glutSwapBuffers();

	last_radius = radius;
	last_angle = angle;
}


void
AlteraTamanhoJanela(GLsizei w, GLsizei h)
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	gluOrtho2D(
		((double) (-view_width * 2.0) / 2.0f),
		((double) (view_width * 2.0) / 2.0f),
		((double) (-view_height * 2.0) / 2.0f),
		((double) (view_height * 2.0) / 2.0f)
	);
}


void
Inicializa (void)
{
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}


void
Timer(int value)
{
	glutPostRedisplay();
	glutTimerFunc(animation_update_period, Timer, 1);
}


int
main(int argc, char **argv)
{
	srand(time(NULL));

	// global initializations
	max_radius = (view_width < view_height) ? (view_width) : (view_height);

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowSize(view_width, view_height);
	glutInitWindowPosition(300, 300);
	glutCreateWindow("Primitivas");
	glutDisplayFunc(Desenha);
	glutReshapeFunc(AlteraTamanhoJanela);
	glutTimerFunc(animation_update_period, Timer, 1);
	Inicializa();
	glutMainLoop();

	return 0;
}


